package com.itheima.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/*
* 最终版
* ConcurrentHashMap版
* */
public class SqlSessionUtils2 {
    public SqlSessionUtils2() {
    }

    private static SqlSessionFactory factory;
    //将获取到的Sqlsession对象和当前的Thread对象实现一一绑定
    //线程域对象，存储的内容属于线程私有的
    //SqlSession不能够定义为成员变量，保证每次用完后都调用close方法，实现资源的归还
    private static Map<Thread,SqlSession> map = new ConcurrentHashMap<>();

    static{
        try {
            InputStream is = Resources.getResourceAsStream("mybatis.xml");
            factory = new SqlSessionFactoryBuilder().build(is);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession openSession(){
        return openSession(false);
    }
    public static SqlSession openSession(boolean autoCommit){
        SqlSession sqlSession = factory.openSession(autoCommit);
        map.put(Thread.currentThread(),sqlSession);
        return sqlSession;
    }
    public static void commit(){
        SqlSession sqlSession = map.get(Thread.currentThread());
        if (sqlSession!=null){
            sqlSession.commit();
        }
    }
    public static void rollback(){
        SqlSession sqlSession = map.get(Thread.currentThread());
        if (sqlSession!=null){
            sqlSession.rollback();
        }
    }
    public static void close(){
        SqlSession sqlSession = map.get(Thread.currentThread());

        if (sqlSession!=null){
            sqlSession.close();
        }
    }
}
